<?php

namespace plugin\admin\app\controller;

use app\services\OrderService;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserProfile;
use support\Request;
use support\Response;
use plugin\admin\app\model\UserTeam;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 分销关系 
 */
class UserTeamController extends Crud
{
    
    /**
     * @var UserTeam
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new UserTeam;
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $level = $request->get('user_level');

        $userId = $request->get('user_id');

        if (empty($userId) && $level) {
            $users = User::where('level', $level)->get()->toArray();
            $ids = array_column($users, 'id');
            if ($ids) {
                $where['user_id'] = ['in', $ids];
            } else {
                $where['user_id'] = 0;
            }
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    public function export(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $limit = 99999999;

        $level = $request->get('user_level');

        $userId = $request->get('user_id');

        if (empty($userId) && $level) {
            $users = User::where('level', $level)->get()->toArray();
            $ids = array_column($users, 'id');
            if ($ids) {
                $where['user_id'] = ['in', $ids];
            } else {
                $where['user_id'] = 0;
            }
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('user-team/index', [
            'userLevels' => UserLevel::all()->pluck('name', 'id')->toArray(),
        ]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('user-team/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('user-team/update');
    }

    protected function formatNormal($items, $total): Response
    {
        $userIds = array_column($items, 'user_id');
        $userProfiles = UserProfile::select(['user_id', 'nickname'])->whereIn('user_id', $userIds)->get()->toArray();
        $userProfiles = array_combine(
            array_column($userProfiles, 'user_id'),
            array_values($userProfiles)
        );

        $users = User::select(['id', 'level'])->whereIn('id', $userIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'id'),
            array_values($users)
        );

        $levels = UserLevel::list();
        $levels = array_combine(
            array_column($levels, 'value'),
            array_column($levels, 'name')
        );

        foreach ($items as $key=>$item) {
            $items[$key]['user_info'] = $userProfiles[$item['user_id']];
            $items[$key]['level_text'] = $levels[$users[$item['user_id']]['level']] ?? '';
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
